<?php
require_once 'pages/TMSFrontUserPage.inc';
require_once 'util/orderprocess.inc';
require_once 'util/TFormPersistance.inc';
require_once 'models/TMSDeliveryModel.inc';

class TDeliveryMethodItem {
	public $Code;
	public $Name;
	public $Cost;
	public $TotalCost;
	
	public function __construct($code,$name,$cost,$total){
		$this->Code = $code;
		$this->Name = $name;
		$this->Cost = $cost;
		$this->TotalCost = $total;
	}
}

class TMSFrontOrderPage extends TMSFrontUserPage {
/**
 * @var TMSOrderModel
 */	
	protected $_ioc_order_model_;
/**
 * @var TMSOrderPositionModel
 */	
	protected $_ioc_order_position_model_;
	
/**
 * @var TMSDeliveryModel
 */	
	protected $_ioc_delivery_model_;
	
/**
 * @var IOrderPostProcessor[]
 */	
	protected $_ioc_order_processor_ = array();
	
	protected $orderAccepted = false;
	
	private $_formdata_;
	
	private $_order_;
	
	public function __construct($path, $filename, TIntrinsicPageService $service){
		parent::__construct($path, $filename, $service);
		$this->_formdata_ = new TFormPersistance($this); 
	}
	
	public function IsParentItem(TMSFrontPageItem $item){return false;}	
	
	public function IsCartEmpty(){
		$cart = $this->Cart->Positions();
		return ($cart->ItemCount() == 0);
	}
	
	public function Positions(){
		return $this->Cart->Positions();
	}	
	
	public function OrderUrl(){
		return $this->Application()->Url().'?&page='.urlencode($this->name);
	}
	
	public function OrderAccepted(){
		return $this->orderAccepted && $this->IsCartEmpty();
	}
	
	public function Handle(THttpRequest $request){
		if($request->article){
			$this->Cart->MakeEmpty();
			$this->Cart->AddPosition($request->article, $request->options?$request->options:array(),$request->count);
		}
		if (isset($request->done)){
			$this->orderAccepted = $request->done;
			unset($request->done);
		}
		parent::Handle($request);
	}

	private function _load_order(){		
		if (!$this->_order_){
			if ($this->OrderAccepted()){
				$this->_order_ = $this->OrderModel->GetItem($this->orderAccepted);
			} else {
				$this->_order_ = $this->OrderModel->GetDummyItem();
				foreach ($this->_formdata_->FormData() As $nm=>$value)
					$this->_order_->$nm = $value;
			}	
		}
		return $this->_order_;
	}
	
	public function Order(){
		return $this->_load_order();
	}
	
	public function OrderProperties(){
		$this->_load_order();
		$properties = $this->_order_->Properties();
		$result = array();
		foreach ($properties as $p)
			if (($p->Name() != 'State') && (!$p->ReadOnly()) && ($p->Type() != TItemPropertyType::PT_COLLECTION)){
				$result[] = $p;
			}
		return $result;
	}
	
	public function CartCost(){
		return $this->Cart->TotalSum();
	}
	
	public function DeliveryMethods(){
		$dms = $this->DeliveryModel->GetList(new TListOptions(array(new TFilterOption('IsActive', TConditionType::C_EQUAL, true)),array(new TSortingOption('OrderNumber'))));
		$result = array();
		foreach ($dms as $dm){
			$cn = $dm->Component;
			$com = $this->Application()->Instantiate($dm->Component, array('name'=>$dm->Code,'container'=>$this));
			foreach ($dm->SetupData as $nm=>$data)
				$com->$nm = $data->value;
			$cost = $com->DeliveryCostByCart($this->Cart);
			$result[] = new TDeliveryMethodItem($dm->Code, (string)$dm, $cost, $cost + $this->CartCost());
		} 
		return new TArrayIterator($result);
	}
	
	public function http_Order(){
		$data = array();
		$props = $this->OrderProperties();
		$this->_formdata_->SaveProperties($props,$data);			
		if (!$this->User){
			$this->checkCaptcha($this->request->captcha);
			if (!trim($this->request->GuestPhone) && !trim($this->request->GuestEmail))
				throw new TExposableException('Необходимо указать контактные данные!');
			foreach ($props as $p){
				$nm = $p->Name();
				if (!isset($this->request->$nm) && $p->Required())
					throw new TExposableException('Поле "'._i($nm).'" не может быть пустым!');	
			}
		} 
		
		/*if ($this->request->comment)
			$data['Comment'] = $this->request->comment;*/
		
		$order = $this->OrderModel->CreateItem($data);
		$cart = $this->Cart->Positions();
		foreach ($cart as $cartpos){
			$discounts = array();
			if ($cartpos->Product->DiscountedPrice){
				foreach ($cartpos->Product->Discounts as $d)
					$discounts[] = $d->Discount->ItemId();
			}
			
			$this->OrderPositionModel->CreateItem(
					array(
						'Order'=>$order->Id,
						'Product'=>$cartpos->Product,
						'Data'=>$cartpos->Data,
						'Quantaty'=>$cartpos->Quantaty,
						'OrderPrice'=>$cartpos->Product->OrderPrice(),
						'AppliedDiscounts'=>join(',',$discounts)
					));
		}		
		$this->Cart->MakeEmpty();
		
		foreach ($this->OrderProcessor as $p){
			$p->ProcessOrder($order);
		}

		$this->orderAccepted = $order->ItemId();
	}
	
	protected function processUrlParameters(array $parameters){
		if ($this->OrderAccepted())
			$parameters['done'] = $this->orderAccepted;
		return $parameters;
	}	
	
	public function FormData($nm){
		return $this->_formdata_->FormData($nm);
	}
}
